package org.dizem.groupon.dao.impl;

import org.dizem.groupon.dao.UserDAO;
import org.dizem.groupon.model.domain.UserEntity;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import java.util.Date;
import java.util.List;

/**
 * User: dizem@126.com
 * Time: 11-6-21 上午10:30
 */
public class UserDAOImpl extends DAOImplSupport<UserEntity> implements UserDAO {

	public UserEntity getById(int id) {
		return (UserEntity) getHibernateTemplate().get(UserEntity.class, id);
	}

	public List<UserEntity> loadAll() {
		return getHibernateTemplate().loadAll(UserEntity.class);
	}

	public List<UserEntity> load(int firstResult, int maxResult) {
		return getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(UserEntity.class), firstResult, maxResult);
	}

	public boolean validatePassword(UserEntity user) {
		Object u = getHibernateTemplate().get(UserEntity.class, user.getId());
		if (u == null)
			return false;
		else
			return ((UserEntity) u).getPassword().equals(user.getPassword());
	}

	public boolean isEmailExisted(String email) {
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.eq("email", email));
		return !getHibernateTemplate().findByCriteria(c).isEmpty();
	}

	public boolean isUsernameExisted(String username) {
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.eq("username", username));
		return !getHibernateTemplate().findByCriteria(c).isEmpty();
	}

	public UserEntity getByUsername(String username) {
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.eq("username", username));
		List users = getHibernateTemplate().findByCriteria(c);
		return users.size() == 0 ? null : (UserEntity) users.get(0);
	}

	public UserEntity getByEmail(String email) {
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.eq("email", email));
		List users = getHibernateTemplate().findByCriteria(c);
		return users.size() == 0 ? null : (UserEntity) users.get(0);
	}

	public List<UserEntity> loadAllAdmins() {
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.eq("accountType", 1));
		return getHibernateTemplate().findByCriteria(c);
	}

	public List<UserEntity> loadAllOrdinaryUsers() {
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.eq("accountType", 0));
		return getHibernateTemplate().findByCriteria(c);
	}

	public int getUserRegisterToday() {
		Date today = new Date();
		today.setHours(0);
		today.setMinutes(0);
		today.setSeconds(0);
		DetachedCriteria c = DetachedCriteria.forClass(UserEntity.class);
		c.add(Restrictions.ge("registerTime", today));
		return getHibernateTemplate().findByCriteria(c).size();
	}
}
